//
//  CollectionViewBaseUseViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/22.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

class CollectionViewBaseUseViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    let disposeBag = DisposeBag()
        
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "34.UICollectionView的使用1：基本用法"
        view.backgroundColor = .white
        
        test()
    }
    
    func test() {
        //定义布局方式以及单元格大小
        let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: 100, height: 70)
        
        Observable.zip(collectionView.rx.itemSelected, collectionView.rx.modelSelected(String.self))
        .bind { [weak self] indexPath, item in
            print("选中项的indexPath为：\(indexPath)")
            print("选中项的标题为：\(item)")
        }
        .disposed(by: disposeBag)
            
        Observable
        .zip(collectionView.rx.itemDeselected, collectionView.rx.modelDeselected(String.self))
        .bind { [weak self] indexPath, item in
            print("被取消选中项的indexPath为：\(indexPath)")
            print("被取消选中项的的标题为：\(item)")
        }
        .disposed(by: disposeBag)
        
        //获取选中并高亮完成后的索引
        collectionView.rx.itemHighlighted.subscribe(onNext: { indexPath in
            print("高亮单元格的indexPath为：\(indexPath)")
        }).disposed(by: disposeBag)
        
        //获取高亮转成非高亮完成后的索引
        collectionView.rx.itemUnhighlighted.subscribe(onNext: { indexPath in
            print("失去高亮的单元格的indexPath为：\(indexPath)")
        }).disposed(by: disposeBag)
        
        //分区头部、尾部将要显示出来的事件响应
        collectionView.rx.willDisplaySupplementaryView.subscribe(onNext: { view, kind, indexPath in
            print("将要显示分区indexPath为：\(indexPath)")
            print("将要显示的是头部还是尾部：\(kind)")
            print("将要显示头部或尾部视图：\(view)\n")
        }).disposed(by: disposeBag)
         
        //创建一个重用的单元格
        collectionView.register(UINib(nibName: "TitleCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
        //初始化数据
        let items = Observable.just([
            "Swift",
            "PHP",
            "Ruby",
            "Java",
            "C++",
            ])
         
        //设置单元格数据（其实就是对 cellForItemAt 的封装）
        items
            .bind(to: collectionView.rx.items) { (collectionView, row, element) in
                let indexPath = IndexPath(row: row, section: 0)
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",
                                                for: indexPath) as! TitleCollectionViewCell
                cell.titleL.text = "\(row)：\(element)"
                return cell
            }
            .disposed(by: disposeBag)
    }

}
